// 缓存类
class Cache {
  constructor() {
    this.type = 'session'
  }

  session() {
    this.type = 'session'
    return this
  }

  local() {
    this.type = 'local'
    return this
  }

  /**
   * 设置缓存
   * @param {string} key
   * @param {*} data
   * @param {number} expire
   */
  set(key, data, expire = 0) {
    if (data === undefined) {
      return true
    }
    expire = this._getExpireTime(expire)
    let cacheData = JSON.stringify({ data: data, expire: expire })

    return this._setCache(key, cacheData)
  }

  /**
   * 获取缓存
   * @param {string} key
   * @param {*} $default
   * @param {boolean} $clear
   */
  get(key, $default = null, $clear = false) {
    let cacheData = this._getCache(key)
    if (!cacheData) return $default
    let result = $default
    let clear = true
    try {
      cacheData = JSON.parse(cacheData)
      if (cacheData && typeof cacheData === 'object' && cacheData.hasOwnProperty('data') && cacheData.hasOwnProperty('expire')) {
        const nowTime = this._getExpireTime(1)
        if ((cacheData.expire > 0 && cacheData.expire > nowTime) || cacheData.expire <= 0) {
          result = cacheData.data
          clear = $clear
        }
      }
    } catch (e) {}
    if (clear) this._removeCache(key)
    return result
  }

  /**
   * 删除缓存
   * @param {string} key
   */
  clear(key) {
    try {
      return this._removeCache(key)
    } catch (e) {
      return false
    }
  }

  /**
   * 换算有效期
   * @param {number} expire
   * @returns {number}
   * @private
   */
  _getExpireTime(expire) {
    if (expire === undefined || expire <= 0) {
      return 0
    }
    return Math.round(new Date() / 1000) + expire
  }

  _setCache(key, data) {
    if (this.type === 'session') {
      return sessionStorage.setItem(key, data)
    } else if (this.type === 'local') {
      return localStorage.setItem(key, data)
    } else {
      return false
    }
  }

  _getCache(key) {
    if (this.type === 'session') {
      return sessionStorage.getItem(key)
    } else {
      return localStorage.getItem(key)
    }
  }

  _removeCache(key) {
    if (this.type === 'session') {
      return sessionStorage.removeItem(key)
    } else {
      return localStorage.removeItem(key)
    }
  }
}

export default new Cache()
